<template>
	<view class="home">
		<view class="blulist">
			<view class="bluitem" v-for="(item,index) in lists" :key="index" @click="createBLEConnection(item)">
				<!-- <image class="img" src="@/static/images/lany.png" mode=""></image> -->
				<view class="con">
					<view class="">
						名称：{{item.name}}
					</view>
					<view class="xinh">
						<view class="">
							信号：
						</view>
						<view class="bottmcall" :style="{width: item.rssi + 'rpx'}">

						</view>
					</view>
					<view class="">
						rssi：{{item.num}}
					</view>
				</view>
				<view class="upr">
					连接设备
				</view>
			</view>
		</view>
		<view class="bottm">
			<view class="search" @click="play" hover-class="checkActive">
				搜索设备
			</view>
		</view>
		<view class="lanya">
			<view class="searchlanya" hover-class="checkActi">
				设备名称：{{lanname}}
			</view>
			<view class="searchlanya" @click="duankai" hover-class="checkActi">
				断开设备
			</view>
		</view>
	</view>
</template>

<script>
	// import vuex from '../../tm-vuetify/tool/function/vuex';
	export default {
		data() {
			return {
				setIf: true,
				sous: true,
				lanname: '',
				num: 50,
				lists: [],
				list: [],
				deviceId: '',
				serviceId: '',
				characteristics: [],
				characteristicId: '',
				iceinfo: false,
				countera: '',
				counterb: '',
				counterr: '',
				resHexitem: '',
				msgall: ['', '0x03', '0x10', '0x00', '0x00', '0x06', '', ''],
				jis: '',
				fff: '',
				deviceList: '',
				cr: null,
				version: '检查更新版本',
				flag: false,
				nub: '',
				flag: false,
				lanyIF: false
			}
		},
		onLoad() {

		},
		onShow() {
			this.lanname = this.vuex_devicename
			console.log('this.vuex_devicename', this.vuex_devicename);
			uni.onBLEConnectionStateChange((res) => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				if (res.connected !== true) {
					console.log('意外断开');
					this.lanname = ''
					uni.$u.vuex('vuex_devicename', '')
					uni.$u.vuex('vuex_deviceId', '')
				}
			})
		},
		onUnload() {

		},
		methods: {
			duankai() {
				uni.closeBLEConnection({
					deviceId: this.vuex_deviceId,
					success: (res) => {
						// uni.showToast({
						// 	title: '设备已断开',
						// 	icon: 'success',
						// 	mask: true,
						// 	duration: 1000
						// });
						this.lanname = ''
						uni.$u.vuex('vuex_devicename', '')
					}
				})

			},
			// 搜索蓝牙
			play() {
				this.duankai()
				this.lanyIF = true
				this.setIf = true
				this.lists = [],
					this.list = [],
					uni.openBluetoothAdapter({
						success: (res) => { //已打开
							uni.getBluetoothAdapterState({ //蓝牙的匹配状态
								success: (res1) => {
									// 开始搜索蓝牙设备
									this.startBluetoothDeviceDiscovery()
								},
								fail(error) {
									uni.showToast({
										icon: 'none',
										title: '获取设备权限失败'
									});
								}
							});
						},
						fail: err => { //未打开 
							uni.showToast({
								icon: 'none',
								title: '查看手机蓝牙是否打开'
							});
						}
					})
			},
			// 开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
				// this.list.length = 0
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						// 发现外围设备
						this.onBluetoothDeviceFound()
					},
					fail: err => {
						console.log(err, '错误信息')
					}
				})
			},
			// 发现外围设备
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					// if(res.devices[0].name == "ESP_SPP_SERVER"){
					if (this.list.indexOf(res.devices[0].deviceId) == -1) {
						this.list.push({
							name: res.devices[0].name,
							deviceId: res.devices[0].deviceId,
							rssi: res.devices[0].RSSI
						})

						this.list = this.list.sort((a, b) => {
							return b.rssi - a.rssi
						})

						const removeDuplicateObj = (arr) => {
							let newArr = []
							let obj = {};
							for (var i = 0; i < arr.length; i++) {
								if (!obj[arr[i].deviceId]) {
									newArr.push(arr[i]);
									obj[arr[i].deviceId] = true;
								}
							}
							return newArr
						};

						this.list = removeDuplicateObj(this.list)
						// this.lists = this.list.filter(item => item.rssi > -90 && item.name !== '')
						this.lists = this.list.filter(item => item.name !== '')
						this.lists = this.lists.map(item => {
							return {
								rssi: item.rssi * -1 * 2,
								num: item.rssi,
								deviceId: item.deviceId,
								name: item.name
							}
						})
						this.sous = false
					}
					// }
				})
			},
			//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						console.log('获取蓝牙设备成功:');
						console.log(res.devices);
					}
				});
			},
			//选择设备连接吧deviceId传进来
			createBLEConnection(deviceId) {
				setTimeout(() => {
					this.setIf = false
				}, 10000)
				uni.showLoading({
					title: '设备连接中...',
					mask: true
				});
				setTimeout(() => {
					uni.hideLoading()
					this.lanyIF = false
				}, 10000)

				uni.$u.vuex('vuex_deviceId', deviceId.deviceId)
				console.log('选择设备连接吧deviceId传进来');
				this.stopBluetoothDevicesDiscovery()
				//data里面建立一个deviceId，存储起来
				this.deviceList = deviceId,
					//连接蓝牙
					setTimeout(() => {
						uni.createBLEConnection({
							// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
							deviceId: deviceId.deviceId,
							success: (res) => {
								this.getBLEDeviceServices()
								console.log('连接蓝牙');
							},
							fail: (res) => {
								if (this.lanyIF) {
									let id = this.deviceList
									this.createBLEConnection(id)
									console.log('失败');
								}
							}
						})
					}, 1500)
			},
			// 停止搜寻蓝牙设备
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						this.loading = false
						// uni.navigateTo({
						// 	url: '/pages/home/show'
						// });
					},

					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				console.log('所有服务', this.deviceList);
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceList.deviceId,
						success: (res) => {
							console.log('蓝牙服务', res);
							if (res.services.length == 0) {
								if (this.setIf) {
									let settim = setTimeout(() => {
										this.getBLEDeviceServices()
									}, 200)
								}
								return
							}
							res.services.forEach((item) => {

								if (item.uuid.indexOf("0000FFF0") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("0000FFE0") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("00001000") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
							})
						}
					})
				}, 1500)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				console.log("进入特征");
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceList.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {
							console.log('特征值', res);
							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {
								if (item.uuid.indexOf("FFF2") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("FFE1") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("0000FFE1") != -1) {
									this.characteristicId = item.uuid
									//console.log('characteristicId:', item.uuid)
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								// EW-DTU02
								if (item.uuid.indexOf("00001001") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("00001002") != -1) {
									this.characteristicId = item.uuid
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 500)
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(characteristicId) {
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceList.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('启用功能success', res)
						this.lanname = this.deviceList.name
						uni.$u.vuex('vuex_devicename', this.deviceList.name)

						setTimeout(() => {
							uni.hideLoading()
							uni.navigateBack({
								delta: 1
							});
						}, 1000)
					},
					fail: (res) => {
						console.log('启用功能fail', res)
						uni.showToast({
							title: '获取服务失败',
							icon: 'fail',
							mask: true,
							duration: 1000
						});
					}
				})

			},
		}
	}
</script>
<style scoped lang="scss">
	.home {
		padding: 20rpx;
		color: #000000;
	}

	.blulist {
		margin-top: 40rpx;
		width: 670rpx;
		height: 70vh;
		padding: 20rpx;
		border-radius: 20rpx;
		overflow: scroll;

		.bluitem {
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 20rpx 0rpx;
			border-bottom: 1rpx solid #d0ccbc;

			.img {
				width: 70rpx;
				height: 70rpx;
			}

			.con {
				width: 400rpx;
				font-size: 25rpx;
			}

			.upr {
				padding: 5rpx 25rpx;
				border-radius: 50rpx;
				background-color: #7a9eaf;
			}
		}
	}

	.bottm {
		width: 710rpx;
		display: flex;
		justify-content: center;

		.search {
			width: 600rpx;
			height: 80rpx;
			margin: 20rpx 0 0 0;
			text-align: center;
			line-height: 80rpx;
			font-size: 35rpx;
			display: flex;
			justify-content: center;
			border-radius: 20rpx;
			background-color: #7a9eaf;
		}

		.checkActive {
			background-color: #526b76;
		}
	}

	.xinh {
		display: flex;
		align-items: center;
	}

	.xinh image {
		width: 300rpx;
		height: 10rpx;
	}

	.bottmcall {
		height: 10rpx;
		background-color: #7a9eaf;
		border-radius: 20rpx;
	}

	.lanya {
		display: flex;
		justify-content: center;

		.searchlanya {
			width: 270rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 30rpx 10rpx;
			padding: 10rpx;
			border-radius: 10rpx;
			font-size: 25rpx;
			background-color: #dcd4c2;
		}

		.checkActi {
			background-color: #a4a59b;
		}
	}

	.renew {
		padding: 10rpx 20rpx;
		margin: 0 auto;
		width: 500rpx;
		text-align: center;
		border-radius: 30rpx;
		font-size: 30rpx;
	}
</style>
<style>
	page {
		background-color: #e9e9e5;
	}
</style>